package com.xing.shirospringboot.config;

import com.xing.shirospringboot.pojo.User;
import com.xing.shirospringboot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import sun.tools.jstat.Token;

/**
 * 用户授权认证
 *
 * @author: xingfuhao
 * @create: 2022-03-13 20:36
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了==》授权");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");

        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();  //拿到user对象

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    //token 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了==》认证");
        //用户名 密码
//        String name="root";
//        String password="123456";
//
//        UsernamePasswordToken userToken=(UsernamePasswordToken) token;
//        if(!userToken.getUsername().equals(name)){
//            //抛出异常 UnkownAccountException
//            return null;
//        }
//        //密码认证，shiro做
//        return new SimpleAuthenticationInfo("",password,"");

        UsernamePasswordToken userToken=(UsernamePasswordToken) token;
        //连接真实的数据库
        User user = userService.queryUserByName(userToken.getUsername());
        if(null == user){
            return null; //UnknownAccountException
        }

        //密码认证，shiro做
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
